<%-- Copyright (c) 2010 Canadensys --%>
<%-- Use utility function to extract request parameters --%>
<%@ page import="net.canadensys.dataportal.vascan.LookupManager" %>
<%@ page import="net.canadensys.dataportal.vascan.TaxonManager" %>
<%@ include file="_inc/functions.jsp" %>
<%  String TEMPLATE_PATH = "/checklist.ftl"; %>
<%@ include file="_inc/ftl/processStart.jsp" %>
<%@ page import="java.sql.ResultSet" %>
<%
try{
    /* request params */
    /* provinces */
    String[] province = null;
    if(request.getParameterValues("province") != null)
     province = request.getParameterValues("province");
    
    /* combination */
    String combination = null;
    if(request.getParameterValues("combination") != null)
        combination = request.getParameter("combination");  
    
    /* habitus */
    String habit = null;
    if(request.getParameter("habit") != null)
        habit = request.getParameter("habit");
    
    /* taxonid */
    int taxon = -1;
    if(request.getParameterValues("taxon") != null)
        taxon = Integer.valueOf(request.getParameter("taxon"));
    
    /* distribution */
    String[] status = null;
    if(request.getParameterValues("status") != null)
        status = request.getParameterValues("status");
    
    /* rank */
    String[] rank = null;
    if(request.getParameterValues("rank") != null)
    	rank = request.getParameterValues("rank");
    
    /* display hybrids */
    String nohybrids = null;
    if(request.getParameter("nohybrids") != null)
        nohybrids = request.getParameter("nohybrids");
    String hybrids = null;
    if(request.getParameter("hybrids") != null)
        hybrids = request.getParameter("hybrids");
    
    /* sort */
    String sort = null;
    if(request.getParameter("sort") != null)
        sort = request.getParameter("sort");
    
    /* limit number of results */
    String nolimit = null;
    if(request.getParameter("nolimit") != null)
        nolimit = request.getParameter("nolimit");
    String limitResults = null;
    if(request.getParameter("limitResults") != null)
    	limitResults = request.getParameter("limitResults");
    
    /* postback values checks & selects */
    // for taxon dropdown list, property selected is added to taxon hashmap
    String checked = "checked=\"checked\"";
    String selected = "selected=\"selected\"";
    HashMap<String,String> habitusSelected = new HashMap<String,String>();
    HashMap<String,String> combinationSelected = new HashMap<String,String>();
    HashMap<String,String> sortSelected = new HashMap<String,String>();
    HashMap<String,String> statusChecked = new HashMap<String,String>();
    HashMap<String,String> rankChecked = new HashMap<String,String>();
    HashMap<String,String> limitResultsChecked = new HashMap<String,String>();
    HashMap<String,String> hybridsChecked = new HashMap<String,String>();
    HashMap<String,String> territoryChecked = new HashMap<String,String>();
    
    if(habit != "" && habit != null){
    	habitusSelected.put(habit.toLowerCase(),selected);
    }
    else{
    	habitusSelected.put("all",selected);
    	habit = "all";
    }
    
    if(combination != "" && combination != null){
    	combinationSelected.put(combination.toLowerCase(),selected);
    }
    else{
    	combinationSelected.put("anyof",selected);
        combination = "anyof";
    }
    
    // get statuses from the querystring. if statuses are empty, force 
    // native, introduced and ephemeral...
    if(status != null){
    	for(String s : status){
    	    statusChecked.put(s.toLowerCase(),checked);
    	}
    }
    else{
    	statusChecked.put("introduced",checked);
    	statusChecked.put("native",checked);
    	statusChecked.put("ephemeral",checked);
        statusChecked.put("excluded",checked);
        statusChecked.put("extirpated",checked);
        statusChecked.put("doubtful",checked);
    	String statuses[] = {"introduced","native","ephemeral","excluded","extirpated","doubtful"};
    	status = statuses;
    }
    
    // checed provinces and territories
    if(province != null){
    	for(String s : province){
    	    territoryChecked.put(s.toUpperCase(),checked);	
    	}
    }    
    
    // hybrids checkbox
    if((nohybrids == null || nohybrids == "") && (hybrids == null || hybrids == "")){
    	hybrids = "true";
    	hybridsChecked.put("display",checked);
    }
    else{
    	if((nohybrids != "" && nohybrids != null) && (hybrids == null || hybrids == "")){
    		   hybrids = null;	
    		   hybridsChecked.put("display","");	   
    	}
    	else{
    		hybrids = "true";   
            hybridsChecked.put("display",checked);
    	}
    }

    // sort options
    if(sort != "" && sort != null){
        sortSelected.put(sort.toLowerCase(),selected);
    }
    else{
    	sort = "taxonomically";
    	sortSelected.put(sort,selected);
    }

    String[] ranks = {
    	    ApplicationConfig.LABEL_RANK_CLASS,checked,
    	    ApplicationConfig.LABEL_RANK_SUBCLASS,
    	    ApplicationConfig.LABEL_RANK_SUPERORDER,
    	    ApplicationConfig.LABEL_RANK_ORDER,
    	    ApplicationConfig.LABEL_RANK_FAMILY,
    	    ApplicationConfig.LABEL_RANK_SUBFAMILY,
    	    ApplicationConfig.LABEL_RANK_TRIBE,
    	    ApplicationConfig.LABEL_RANK_SUBTRIBE,
    	    ApplicationConfig.LABEL_RANK_GENUS,
    	    ApplicationConfig.LABEL_RANK_SUBGENUS,
    	    ApplicationConfig.LABEL_RANK_SECTION,
    	    ApplicationConfig.LABEL_RANK_SUBSECTION,
    	    ApplicationConfig.LABEL_RANK_SERIES,
    	    ApplicationConfig.LABEL_RANK_SPECIES,
    	    ApplicationConfig.LABEL_RANK_SUBSPECIES,
    	    ApplicationConfig.LABEL_RANK_VARIETY
    };
    
    // init all ranks as checked
    for(String r : ranks){
    	rankChecked.put(r,checked);	
    }
    // check main_rank & sub_rank "All" checkbox since all ranks are checked
    rankChecked.put("main_rank",checked);
    rankChecked.put("sub_rank",checked);
    
    // if rank is received from querystring, reinit all ranks to unchecked and only check ranks present in querystring
    int main_rank = 0;
    int sub_rank = 0;
    if(rank != null){
    	for(String r : ranks){
            rankChecked.put(r,""); 
        }
        rankChecked.put("main_rank","");
        rankChecked.put("sub_rank","");
    	for(String r : rank){
    		rankChecked.put(r.toLowerCase(),checked);
    		if(r.toLowerCase().equals(ApplicationConfig.LABEL_RANK_CLASS) ||
    		r.toLowerCase().equals(ApplicationConfig.LABEL_RANK_ORDER) ||
    		r.toLowerCase().equals(ApplicationConfig.LABEL_RANK_FAMILY) ||
    		r.toLowerCase().equals(ApplicationConfig.LABEL_RANK_GENUS) ||
    		r.toLowerCase().equals(ApplicationConfig.LABEL_RANK_SPECIES))
    			main_rank++;
    		else
    			sub_rank++;
    	}
    }
    // there must be a better way to do this... maybe only with jquery stuff... 
    if(main_rank ==  5)
        rankChecked.put("main_rank",checked);
    if(sub_rank ==  11)
        rankChecked.put("sub_rank",checked);  
    
    // limit checkbox
    if(nolimit == null && limitResults == null){
        limitResults = "true";
        limitResultsChecked.put("display",checked);
    }
    else if(nolimit != null && limitResults != null){
        limitResults = "true";  
        limitResultsChecked.put("display",checked);       
    }
    else{
    	limitResults = "";
    	limitResultsChecked.put("display","");
    }

    /* */  
    boolean searchOccured = false;
    int totalResults = 0;
    Vector<HashMap<String,Object>> taxonDistributions = new Vector<HashMap<String,Object>>();
    if(taxon != -1){
    //if(combination != null && habitus != null && taxon != 0 && status != null && province != null){
    	searchOccured = true;
    	boolean returnCountOnly = true;
        int limitResultsTo = 0;
        ResultSet rs = LookupManager.getDistributions(returnCountOnly, limitResultsTo, combination, habit, taxon, province, status, rank, hybrids, sort);
        if(rs != null){
        	rs.next(); totalResults = rs.getInt(1);
        }
		
        returnCountOnly = false;
        if(limitResults.equals("true"))
        	limitResultsTo = 200;
        
        rs = LookupManager.getDistributions(returnCountOnly, limitResultsTo, combination, habit, taxon, province, status, rank, hybrids, sort);
        if(rs !=null){
        	rs.beforeFirst();
            while(rs.next()){
                   HashMap<String,Object> distributionData = new HashMap<String,Object>();
                   distributionData.put("fullScientificName",rs.getString("calnamehtml"));
                   distributionData.put("taxonId",rs.getInt("taxonid"));
                   distributionData.put("rank",rs.getString("rank"));
                   Vector<HashMap<String,Object>> taxonHabitus = new Vector<HashMap<String,Object>>();
                   String habituses[] = rs.getString("calhabit").split(",");
                   if(habituses != null){
                	   for(String h : habituses){
                		   HashMap<String,Object> habitusData = new HashMap<String,Object>();
                		   habitusData.put("habit",h);
                		   taxonHabitus.add(habitusData);
                	   }
                   }
                   distributionData.put("habit",taxonHabitus);
                   distributionData.put("AB",rs.getString("AB"));
                   distributionData.put("BC",rs.getString("BC"));
                   distributionData.put("GL",rs.getString("GL"));
                   distributionData.put("NL_L",rs.getString("NL_L"));
                   distributionData.put("MB",rs.getString("MB"));
                   distributionData.put("NB",rs.getString("NB"));
                   distributionData.put("NL_N",rs.getString("NL_N"));
                   distributionData.put("NT",rs.getString("NT"));
                   distributionData.put("NS",rs.getString("NS"));
                   distributionData.put("NU",rs.getString("NU"));
                   distributionData.put("ON",rs.getString("ON"));
                   distributionData.put("PE",rs.getString("PE"));
                   distributionData.put("QC",rs.getString("QC"));
                   distributionData.put("PM",rs.getString("PM"));
                   distributionData.put("SK",rs.getString("SK"));
                   distributionData.put("YT",rs.getString("YT"));
                   taxonDistributions.add(distributionData);
            }
            
            if(!limitResults.equals("true"))
                totalResults = taxonDistributions.size();
        }
    }
    root.put("distributions",taxonDistributions);
    root.put("habit",habitusSelected);
    root.put("sort",sortSelected);
    root.put("hybrids",hybridsChecked);
    root.put("status",statusChecked);
    root.put("limitResults",limitResultsChecked);
    root.put("rank",rankChecked);
    root.put("combination",combinationSelected);
    root.put("territory",territoryChecked);
    root.put("taxons",TaxonManager.getChecklistTaxons(taxon));
    root.put("isSearch",searchOccured);
    root.put("numResults",totalResults);
   
    
    
}
catch(Exception e){
    e.printStackTrace();
    //out.write(e.toString());
}
%>
<%@ include file="_inc/ftl/processStop.jsp" %>